package multiThreading.producerConsumerSimple;

public class Buffer {
	private  int count = 0 ;
	private final int MAX = 3;
	
	/**
	 * Only for the producer
	 */
	public synchronized void insert(){
		if(count==MAX){
			try {
				System.out.println(Thread.currentThread().getName()+" waiting "+count);
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		else if(count<MAX){
			System.out.println(Thread.currentThread().getName()+" inserting "+ count++);
			if(count==MAX){
				System.out.println(Thread.currentThread().getName()+" notify every one "+count);
				notifyAll();
			}
		}
	}
	
	/**
	 * Only for the consumer
	 */
	public synchronized  void remove(){
		if(count == 0){
			try {
				System.out.println(Thread.currentThread().getName()+" waiting "+count);
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else if (count > 0){
			System.out.println(Thread.currentThread().getName()+" removing "+ count--);
			if(count==0){
				System.out.println(Thread.currentThread().getName()+" notify every one "+count);
				notifyAll();
			}
		}
	}
	
}
